package com.streambolics.mail;

import javax.mail.Multipart;
import javax.mail.Part;

import com.streambolics.std.StringExtensions;

public abstract class MimeParser
{
    protected void dispatch (Part aPart) throws Exception
    {
        String mimeType = aPart.getContentType ();
        if (mimeType == null)
        {
            mimeType = "text/unrecognized";
        }
        dispatch (StringExtensions.before (mimeType, "/"), StringExtensions.after (mimeType, "/"), (String) aPart.getContent ());
    }

    protected abstract void dispatch (String aMimeType, String MimeSubType, String aContent) throws Exception;

    public void parse (Part aPart) throws Exception
    {
        if (aPart.isMimeType ("multipart/*"))
        {
            Multipart mp = (Multipart) aPart.getContent ();
            for (int i = 0; i < mp.getCount (); i++)
            {
                parse (mp.getBodyPart (i));
            }
        }
        else
        {
            dispatch (aPart);
        }
    }
}
